package com.thh.shirodemo.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.AllSuccessfulStrategy;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2022-07-18-0:01
 */
@Configuration
public class ShiroConfig {
//    //1.realm 代表系统资源
//    @Bean
//    public Realm myRealm(){
//        return new MyRealm();
//    }
    //2.SecurityManager(做流程控制)
    @Bean
    public DefaultWebSecurityManager mySecurityManager(AuthorizingRealm myRealm, AuthenticatingRealm userIdRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置加密
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密算法
        matcher.setHashAlgorithmName("MD5");

        //设置加密的迭代次数
        matcher.setHashIterations(3);
        //用该matcher加密我们的realm
        myRealm.setCredentialsMatcher(matcher);
        userIdRealm.setCredentialsMatcher(matcher);
//        securityManager.setRealm(myRealm);
        securityManager.setRealms(Arrays.asList(myRealm,userIdRealm));

        //设置认证策略
        ModularRealmAuthenticator authenticator=new ModularRealmAuthenticator();

        authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        authenticator.setRealms(Arrays.asList(myRealm,userIdRealm));
        securityManager.setAuthenticator(authenticator);
        return securityManager;
    }

    //3.ShiroFilterFactoryBean 请求过滤器
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager mySecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(mySecurityManager);
        //配置路径过滤器
        Map<String,String> filterMap=new HashMap<>();
        //key是ant路径 value配置shiro的默认过滤器
        //Shiro的默认过滤器,配置DefaultFilter中的key
        //auth,authc,perms,role

        //表示两个资源路径都需要登录才可以访问
//        filterMap.put("/mobile/**","authc,perms[mobile]");
//        filterMap.put("/salary/**","authc,perms[salary]");


        //配置登出 登出返回到下方设置的登录页
        filterMap.put("/common/logout","logout");
        //配置我们的登录页
        factoryBean.setLoginUrl("/index.html");

        factoryBean.setFilterChainDefinitionMap(filterMap);
        //配置我们的未授权页面
        factoryBean.setUnauthorizedUrl("/common/unauthorized");
        return factoryBean;
    }
}
